package com.acmen.easyapi.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 驼峰转换
 *
 * @Author acmen
 */
public class HumpUtil {

    //转变的依赖字符
    public static final char UNDERLINE = '_';

    /**
     * 将驼峰转换成"_"(userId:user_id)
     *
     * @param param
     * @return
     */
    public static String hump2underline(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append(UNDERLINE);
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 将"_"转成驼峰(user_id:userId)
     *
     * @param param
     * @return
     */
    public static String underline2hump(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        if(param.endsWith("_")){
            return underline2hump(param.substring(0,param.length()-1))+"_";
        }
        if(param.startsWith("_")){
            return "_"+underline2hump(param.substring(1));
        }
        StringBuilder sb = new StringBuilder(param);
        Matcher mc = Pattern.compile(UNDERLINE + "").matcher(param);
        int i = 0;
        while (mc.find()) {
            int position = mc.end() - (i++);
            sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase());
        }
        return sb.toString();
    }

    /*
     * 测试
     */
    public static void main(String[] args) {
        System.out.println(hump2underline("accountAll"));
        System.out.println(underline2hump("account_all"));
    }
}
